//
//  BaiduFacePlugin.m
//  baidu_face
//
//  Created by huangshuigen on 2024/8/26.
//

#import "BaiduFacePlugin.h"
#import "BaiduApi.h"
#import "FaceParameterConfig.h"
#import "BDFaceAdjustParamsTool.h"
#import "BDConfigDataService.h"
#import "BDFaceVerificationConstant.h"
#import "BDFaceVerificationController.h"

#import <BDFaceLogicLayer/BDFaceLogicLayer.h>
#import <BDFaceBaseKit/BDFaceBaseKit.h>
#import "ActivityIndicatorManager.h"


@interface BaiduFacePlugin()
@property (nonatomic, strong) NSString *ak;
@property (nonatomic, strong) NSString *sk;
@property (nonatomic, strong) NSString *lk;
@property (nonatomic, strong) NSString *planId;
@property (nonatomic, strong) NSString *accessToken;
@property (nonatomic, strong) NSString *verifyToken;
@property (nonatomic, strong) BDFaceLogicService *logicService;
@property (nonatomic, assign) NSInteger faceInitCode;
//  请求accesstoken结果回调
typedef void (^resultBlock)(BOOL result);
@end

@implementation BaiduFacePlugin



+(void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel
            methodChannelWithName:@"baidu_face"
                  binaryMessenger:[registrar messenger]];
    BaiduFacePlugin* instance = [[BaiduFacePlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary<NSString*, id>* args = call.arguments;
    if ([@"init" isEqualToString:call.method]) {

        _ak = args[@"ak"];
        _sk = args[@"sk"];
        _lk = args[@"licenseKey"];
        _planId = args[@"planId"];
        [self getAccessTokenWithAk:^{}];
        // 默认初始化SDK参数配置+鉴权
        [self initFaceServiceAndInfoCollectService];
        result(@"success");
    } else if ([@"liveDetect" isEqualToString:call.method]) {

        __weak typeof(self) weakSelf = self;
        if (_faceInitCode != 1000) {
            [self initFaceSDK];
        }
        if (_accessToken == nil || [_accessToken isEqual:@""]) {
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            [[ActivityIndicatorManager sharedManager] showIndicator];
            dispatch_async(queue, ^{
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                [weakSelf getAccessTokenWithAk:^{
                    dispatch_semaphore_signal(semaphore);
                    [[ActivityIndicatorManager sharedManager] hideIndicator];
                }];
            });
            dispatch_async(queue, ^{
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                [weakSelf startVerificationProcessWithResult:result];
                dispatch_semaphore_signal(semaphore);
            });
        } else {
            [weakSelf startVerificationProcessWithResult:result];
        }

    } else {
        result(FlutterMethodNotImplemented);
    }
}


- (void)startVerificationProcessWithResult:(id)result {
    if (_accessToken == nil || [_accessToken isEqual:@""]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [BDFaceToastView showToast:[UIApplication sharedApplication].keyWindow text: @"网络开小差了,请重试!"];
        });
        return;
    }
    __weak typeof(self) weakSelf = self;

    // 设置验证类型
    [BDFaceVerificationConstant sharedInstance].verifyType = BDFaceVerificationLiveCheck;

    // 显示加载指示器
    [[ActivityIndicatorManager sharedManager] showIndicator];

    // 请求 verify_token
    [weakSelf getVerifyToekenResult:result];
    [[NSNotificationCenter defaultCenter] observationInfo];
}

- (void)getAccessTokenWithAk:(void (^ __nullable)(void))completion{

    __weak typeof(self) weakSelf = self;
    NSURL *url = [NSURL URLWithString:[BaiduApi accessTokenUrl:_ak sk:_sk]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:BDFaceRequestTokenMaxTime];
    [request setHTTPMethod:@"GET"];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    configuration.timeoutIntervalForRequest = BDFaceRequestTokenMaxTime;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary *responseDic = [NSJSONSerialization JSONObjectWithData: data
                                                                               options: NSJSONReadingMutableContainers
                                                                                 error: &error];
            NSString *tokenString = responseDic[@"access_token"];
            if (tokenString) {
                weakSelf.accessToken = tokenString;
                completion();
            }else{
                completion();
            }
            NSLog(@"%@", responseDic);
        }else{
            completion();
        }
    }];
    [task resume];
}

/**
 初始化人脸和OCR SDK
 */
- (void)initFaceServiceAndInfoCollectService {
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;

    __weak typeof(self) this = self;
    /// 初始化 人脸识别Service
    this.logicService = [[BDFaceLogicService alloc] initWithController:vc face:^{
        [this initFaceSDK];
    } ocr:^{
        //        [this initOcrSDK];
    }];
}

/*
 初始化人脸SDK
 */
- (void)initFaceSDK {
    BDFaceBaseKitLivenessTipCustomConfigItem *tipCustomConfigItem = [[BDFaceBaseKitLivenessTipCustomConfigItem alloc] initWithLivenessTipConfig];
    [[BDFaceBaseKitManager sharedInstance] setFaceSdkCustomLivenessTipConfig:tipCustomConfigItem];
    //设置默认人脸参数
    BDFaceBaseKitParamsCustomConfigItem *paramsCustomConfigItem = [[BDFaceBaseKitParamsCustomConfigItem alloc] initWithParamsConfig];
    [[BDFaceBaseKitManager sharedInstance] setParamsCustomConfigItem:paramsCustomConfigItem];
    //设置默认UI参数
    BDFaceBaseKitUICustomConfigItem *uiCustomConfigItem = [[BDFaceBaseKitUICustomConfigItem alloc] initWithUIConfig];
    /// 采集SDK只回调结果，不显示后续页面UI
    [BDFaceBaseKitManager sharedInstance].paramsCustomConfigItem.isIntoResultView = NO;
    // 非安全版本控制中英文切换logo隐藏
    //    [BDFaceBaseKitManager sharedInstance].paramsCustomConfigItem.isShowLanguageSwitch = NO;
    [[BDFaceBaseKitManager sharedInstance] setUiCustomConfigItem:uiCustomConfigItem];
    __weak typeof(self) weakSelf = self;
    /// 设置licence_id 和license_name
    [[BDFaceBaseKitManager sharedInstance] initCollectWithLicenseID:_lk andLocalLicenceName:FACE_LICENSE_NAME andExtradata:@{} callback:^(BDFaceInitRemindCode code, NSDictionary *extradata) {
        NSLog(@"%@",weakSelf.lk);
        NSLog(@"%@",FACE_LICENSE_NAME);
        NSLog(@"人脸初始化结果：%ld", (long)code);
        weakSelf.faceInitCode = code;
    }];
    // 设置图像阀值
    [BDFaceAdjustParamsTool changeConfig:[BDConfigDataService faceImageParams]];
}


- (void)getVerifyToekenResult:(FlutterResult)result{
    __weak typeof(self) this = self;
    // 获取verifytoken接口
    // 开放api url后面拼接的accesstoken需要请求获取避免过期 确保aksk正确
    NSString *verifyTokenUrl = [BaiduApi verifyTokenWithAccessToken:_accessToken];
    // demo测试数据
    NSDictionary *tokenDic = @{@"plan_id":_planId, @"match_source": @(2)};
    NSURL *url = [NSURL URLWithString:verifyTokenUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:BDFaceRequestTokenMaxTime];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tokenDic options:NSJSONWritingPrettyPrinted error:nil];
    if (jsonData != nil && [jsonData isKindOfClass:[NSData class]]) {
        [request setHTTPBody:jsonData];
    }
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    configuration.timeoutIntervalForRequest = BDFaceRequestTokenMaxTime;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary *responseDic = [NSJSONSerialization JSONObjectWithData: data
                                                                               options: NSJSONReadingMutableContainers
                                                                                 error: &error];
            dispatch_async(dispatch_get_main_queue(), ^{
                id successPointer = responseDic[@"success"];
                BOOL success = [successPointer boolValue];
                if (success) {
                    NSString *tokenString = responseDic[@"result"][@"verify_token"];
                    this.verifyToken = tokenString;
                    [[ActivityIndicatorManager sharedManager] hideIndicator];
                    // 调用人脸采集相关接口
                    // 视频路径返回属性默认
                    [BDFaceBaseKitManager sharedInstance].paramsCustomConfigItem.recordAbility = YES;
                    [BDFaceBaseKitManager sharedInstance].paramsCustomConfigItem.conditionTimeout = 60;
                    //                [BDFaceBaseKitManager sharedInstance].paramsCustomConfigItem.isColorType = NO;
                    //                [BDFaceBaseKitManager sharedInstance].paramsCustomConfigItem.isCheckColorfulLive = NO;


                    [self startLiveCheckResult:result];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[ActivityIndicatorManager sharedManager] hideIndicator];
                        [BDFaceToastView showToast:[UIApplication sharedApplication].keyWindow text: @"服务异常"];
                    });
                }
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[ActivityIndicatorManager sharedManager] hideIndicator];
                [BDFaceToastView showToast:[UIApplication sharedApplication].keyWindow text: @"服务异常"];
            });
        }
    }];
    [task resume];
}


/// 开始做活体检测
- (void)startLiveCheckResult:(FlutterResult)result {
    NSDictionary *tokenDic = @{BDFaceLogicServiceTokenKey : _accessToken ?: @""};
    //设置默认人脸参数
    [_logicService startRecognizeToCheckLive:tokenDic callBack:^(int resultCode, NSDictionary * _Nonnull resultDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 0 表示成功
            if (resultCode == 0) {
                NSDictionary *responseDic = resultDic[@"data"];
                int code = [responseDic[@"error_code"] intValue];
                if (code == 0) {

                    NSString *base64Image = [responseDic objectForKey:@"dec_image"];

                    NSArray *base64ImageArray = [responseDic objectForKey:@"dec_image"];
                    if ([base64ImageArray isKindOfClass:[NSArray class]]) {
                        NSArray *tempArray = (NSArray *)base64ImageArray;
                        if (tempArray.count > 0) {
                            base64Image = tempArray[0];
                        }
                    }
                    if (base64Image) {
                        NSMutableDictionary *params = [NSMutableDictionary dictionary];
                        [params setValue:@(resultCode) forKey:@"resultCode"];
                        [params setValue:base64Image forKey:@"resultImage"];

                        result(params);
                    } else {
                        result([FlutterError errorWithCode:@"-1" message:@"message" details:@"base64Image为nil"]);
                    }
                }else{
                    result(@{@"resultCode":@(code)});
                }
            } else {
                UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
                NSString *errorMessage = resultDic[BDFaceLogicServiceReturnKeyForResultMsg];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [BDFaceToastView showToast:vc.view text:errorMessage];
                });
            }

        });
    }];
}



@end
